const { get, run, all } = require('../config/db');

class ProtocolCategory {
  // 创建协议分类
  static async create(name, description, userId, isPublic = false) {
    try {
      const result = await run(
        'INSERT INTO protocol_categories (name, description, user_id, is_public) VALUES (?, ?, ?, ?)',
        [name, description, userId, isPublic ? 1 : 0]
      );
      
      return { id: result.id, name, description, userId, isPublic };
    } catch (error) {
      console.error('创建协议分类失败:', error);
      throw error;
    }
  }
  
  // 获取用户的所有协议分类
  static async findByUserId(userId) {
    try {
      const rows = await all(
        'SELECT * FROM protocol_categories WHERE user_id = ? OR is_public = 1 ORDER BY name',
        [userId]
      );
      
      return rows;
    } catch (error) {
      console.error('获取协议分类失败:', error);
      throw error;
    }
  }
  
  // 通过ID查找协议分类
  static async findById(id) {
    try {
      const category = await get(
        'SELECT * FROM protocol_categories WHERE id = ?',
        [id]
      );
      
      return category || null;
    } catch (error) {
      console.error('查找协议分类失败:', error);
      throw error;
    }
  }
  
  // 更新协议分类
  static async update(id, name, description, isPublic) {
    try {
      await run(
        'UPDATE protocol_categories SET name = ?, description = ?, is_public = ? WHERE id = ?',
        [name, description, isPublic ? 1 : 0, id]
      );
      
      return { id, name, description, isPublic };
    } catch (error) {
      console.error('更新协议分类失败:', error);
      throw error;
    }
  }
  
  // 删除协议分类
  static async delete(id) {
    try {
      await run(
        'DELETE FROM protocol_categories WHERE id = ?',
        [id]
      );
      
      return true;
    } catch (error) {
      console.error('删除协议分类失败:', error);
      throw error;
    }
  }
}

module.exports = ProtocolCategory;
